package com.chaihu.jpaDemo.modules.system.controller;

import com.alibaba.fastjson.JSON;
import com.chaihu.jpaDemo.common.searchBean.SearchCondition;
import com.chaihu.jpaDemo.common.util.DateUtil;
import com.chaihu.jpaDemo.common.util.ReflectUtil;
import com.chaihu.jpaDemo.common.util.convertVo.ConverterVoUtils;
import com.chaihu.jpaDemo.modules.common.controller.BaseController;
import com.chaihu.jpaDemo.modules.common.dto.ResultObject;
import com.chaihu.jpaDemo.modules.system.dto.LogDto;
import com.chaihu.jpaDemo.modules.system.dto.OperateLogVo;
import com.chaihu.jpaDemo.modules.system.entity.OperateLog;
import com.chaihu.jpaDemo.modules.system.service.OperateLogService;
import com.chaihu.jpaDemo.utils.BeanUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述: 日志控制器类
 * 作者: qinzhw
 * 创建时间: 2018-07-16 16:07
 **/
@RestController
@RequestMapping("/sys/log")
@Api(tags = "日志管理", description = "增删查改")
public class OperateLogController extends BaseController {

    @Autowired
    OperateLogService logService;

    /*{"autoCount":false,"conditionList":[{"code":"userName","operator":"LIKE","type":"string","value":"客"}],
    "pageNumber":1,"pageSize":10,"sortList":[{"field":"id","style":"DESC"}]}*/
    @PostMapping("list2")
    @ApiOperation(value = "日志列表2", notes = "日志列表2")
    @ApiImplicitParam(name = "", value = "任意条件", required = true, paramType = "json")
    public ResultObject<?> list2(@ApiParam(name="查询条件",value="json格式",required=true)
                                     @RequestBody SearchCondition<OperateLog> condition) {
        Map<String, Object> parameterValueMap = condition.getParameterValueMap();
        Map<String, Object> paramsMap = condition.getParameterMap();
        PageRequest pageRequest = buildPageRequest(condition);

        Page<OperateLog> dicts = logService.findAll(paramsMap,pageRequest);
        return ResultObject.ok(dicts);
    }

    /*{"EQ_userName":"访客","pageNum":"1","pageSize":"5","sort":["id"],"sortType":["DESC"]}*/
    @PostMapping("list")
    @ApiOperation(value = "日志列表", notes = "日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "EQ_userName", value = "操作用户名", required = false, paramType = "query")
    })
    public ResultObject<?> list(@RequestBody HashMap<String,Object> map) {
        Map<String, Object> paramsMap = getParameterMap();
        paramsMap.putAll(map);
        PageRequest pageRequest = buildPageRequest(paramsMap);
        Page<OperateLog> dicts = logService.findAll(pageRequest);


        /**************测试原生封装查询start***************/
        Page<OperateLog> all =      logService.findAll(paramsMap, pageRequest);
        Page<OperateLogVo> all1 =   logService.findAll(paramsMap, pageRequest, OperateLogVo.class);
        List<OperateLog> all2 =     logService.findAll(paramsMap, pageRequest.getSort());
        List<OperateLogVo> all3 =   logService.findAll(paramsMap, pageRequest.getSort(), OperateLogVo.class);
        List<OperateLog> all4 =     logService.findAll(paramsMap);
        /**************测试原生封装查询end ***************/


        /**************测试自定义封装查询start***************/
        //测试分页
        String sql = "SELECT l.*,u.`account` FROM `sys_operate_log` l, `sys_user` u WHERE l.`user_id` = u.`id` AND l.`id`<100 ";
        // String jpql = "SELECT l,u.account FROM OperateLog l,User u where l.userId = u.id and l.id<100 ";
        //String sql = "SELECT * FROM `sys_operate_log` where 1=1 and id<100 ";
        String jpql = "SELECT l FROM OperateLog l where 1=1 and l.id<100 ";
        //自定义属性映射对象属性即可 "SELECT * FROM (SELECT l.*,l.`user_name` AS user_nametemp FROM `sys_operate_log` l) tmp WHERE 1=1 ";
        PageRequest page=new PageRequest(0,2,new Sort(Sort.Direction.DESC, "id"));

        HashMap<String,Object> sqlParams = new HashMap<String,Object>();
        sqlParams.put("EQ_l.userName","qin");
        HashMap<String,Object> jpqlParams = new HashMap<String,Object>();
        jpqlParams.put("EQ_l.userName","qin");

        Page<OperateLog> page3 = logService.getPageVo(sql, page, OperateLog.class);
        List<OperateLog> list2 = logService.getListVo(sql,  OperateLog.class);
        Page<OperateLog> data1 = logService.findPageByJPQL(jpql, jpqlParams,OperateLog.class, page);
        List<OperateLog> data2 = logService.findListByJPQL(jpql, jpqlParams,OperateLog.class, new Sort(Sort.Direction.ASC, "id"));
        Page<OperateLog> data3 = logService.findPageByNativeSQLAndParams(sql, sqlParams, OperateLog.class, page);
        List<OperateLog> data4 = logService.findListByNativeSQLAndParams(sql, sqlParams, OperateLog.class, new Sort(Sort.Direction.ASC, "id"));

        Page<LogDto> page2 = logService.getPageVo(sql, page, LogDto.class);
        List<LogDto> list1 = logService.getListVo(sql,  LogDto.class);
        Page<LogDto> data5 = logService.findPageByJPQL(jpql, jpqlParams,LogDto.class, page);
        List<LogDto> data6 = logService.findListByJPQL(jpql, jpqlParams,LogDto.class,  new Sort(Sort.Direction.ASC, "id"));
        Page<LogDto> data8 = logService.findPageByNativeSQLAndParams(sql, sqlParams, LogDto.class, page);
        List<LogDto> data7 = logService.findListByNativeSQLAndParams(sql, sqlParams, LogDto.class, new Sort(Sort.Direction.ASC, "id"));

        List<Map<String, Object>> map1 = logService.getMap(sql);
        List<List<Object>> getlist =     logService.getList(sql);

        Page<OperateLog> page0 =    logService.findPageByNativeSQL(sql, page);
        Page<OperateLogVo> page1 =  logService.findPageByNativeSQL(sql, OperateLogVo.class, page);
        List<OperateLog> list4 =    logService.findListByNativeSQL(sql, page.getSort());
        List<LogDto> list3 =        logService.findListByNativeSQL(sql, LogDto.class, page.getSort());
        /**************测试自定义封装查询end ***************/

        /**************测试数据字典翻译start***************/
        //以Field name 为key 从缓存中取值 DictAllTypeCache
        //测试 ConverterVoUtils 对象转换 翻译
        OperateLogVo vo =       ConverterVoUtils.dataConvert(dicts.getContent().get(0), OperateLogVo.class);
        OperateLogVo logVo =    ConverterVoUtils.dataObjConvert(dicts.getContent().get(0), new OperateLogVo());
        List<OperateLogVo> logVos = ConverterVoUtils.dataConverts(new ArrayList<>(dicts.getContent()), OperateLogVo.class);
        List listVo = ConverterVoUtils.dataConverts2(Lists.newArrayList(dicts.getContent()), OperateLogVo.class, ArrayList.class);
        ArrayList list = ConverterVoUtils.dataConverts2(Lists.newArrayList(dicts.getContent()), OperateLogVo.class, ArrayList.class);
        List<OperateLogVo> listVo1 = ConverterVoUtils.dataConverts(new ArrayList<>(dicts.getContent()), OperateLogVo.class);

       //测试 ReflectUtil 添加 字典翻译属性
       ResultObject.ok(ReflectUtil.translationToVo(dicts.getContent()));

       //测试 通过@CacheFormat MyResultTransformer 翻译
        Page<OperateLogVo> page5 = logService.findPageByNativeSQL(sql, OperateLogVo.class, page);
        /**************测试数据字典翻译end ***************/

        return ResultObject.ok(dicts);
    }

    @GetMapping("{id}")
    @ApiOperation(value = "日志查询对象", notes = "根据ID查询")
    @ApiImplicitParam(name = "id", value = "表ID", required = true, dataType = "Long", paramType = "path")
    public ResultObject<OperateLog> findById(@PathVariable Long id) throws IllegalArgumentException {
        return ResultObject.ok(ReflectUtil.translationToVo(logService.findOne(id)));
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "日志删除", notes = "根据ID删除（逻辑删除）")
    @ApiImplicitParam(name = "id", value = "表ID", required = true, dataType = "Long", paramType = "path")
    public ResultObject<?> deleteById(@PathVariable Long id) {
        logService.deleteById(id);
        return ResultObject.ok("删除成功");

    }

    @PostMapping
    @ApiOperation(value = "日志新增", notes = "公共新增方法")
    @ApiImplicitParam(name = "operateLog", value = "具体业务对象json", required = true, dataType="OperateLog" ,paramType = "body")
    public ResultObject<?> add(@Valid @RequestBody OperateLog operateLog, BindingResult br) {
        logger.info("happenTime:{},event:新增对象,param:{}", DateUtil.getNowYYYYMMDDHHMMSS(), JSON.toJSONString(operateLog));

        if (br.hasErrors()){
            return ResultObject.error(getValidErrorMsg(br));
        }

        OperateLog e = logService.save(operateLog);
        if (e != null) {
            return ResultObject.ok("新增成功");
        }
        return ResultObject.error("新增失败");
    }

    @PutMapping
    @ApiOperation(value = "日志修改", notes = "修改日志方法")
    @ApiImplicitParam(name = "operateLog", value = "具体业务对象json", required = true, dataType ="OperateLog" ,paramType = "body")
    public ResultObject<?> modify(@RequestBody OperateLog operateLog) {
        logger.info("happenTime:{},event:更新对象,param:{}", DateUtil.getNowYYYYMMDDHHMMSS(), JSON.toJSONString(operateLog));

        OperateLog target = logService.findOne( operateLog.getId());
        if (target == null) {
            return ResultObject.error("对象不存在");
        }
        BeanUtil.copyPropertiesIgnoreNull(operateLog,target);
        OperateLog e = logService.save(target);
        if (e != null) {
            return ResultObject.ok("更新成功");
        }
        return ResultObject.error("更新失败");

    }
}
